<template>
  <view class="cx-print-index">
    <!-- 打印弹框 -->
    <u-popup
      class="u-pop"
      :show="printShows"
      :round="6"
      mode="center"
      :closeOnClickOverlay="false"
    >
      <view class="popup-view">
        <view class="title-view">
          <view class="text-view">打印</view>
          <u-icon
            @click="
              () => {
                printShows = false;
              }
            "
            name="close"
            color="#999"
            size="20"
          ></u-icon>
        </view>
        <view class="cell-item" @click="toPrinter">
          <view class="label">设备</view>
          <view class="value-view flex">
            <text>设备1</text>
            <u-icon name="arrow-right" color="#ddd" size="16"></u-icon>
          </view>
        </view>
        <view class="cell-item" @click="toReport">
          <view class="label">报表</view>
          <view class="value-view flex">
            <text>{{ print.document.name || "" }}</text>
            <u-icon name="arrow-right" color="#ddd" size="16"></u-icon>
          </view>
        </view>
        <view class="cell-item">
          <view class="label">份数</view>
          <view class="value-view flex">
            <u--input border="none"></u--input>
            <u-icon name="arrow-right" color="#ddd" size="16"></u-icon>
          </view>
        </view>

        <view class="bot-view flex flex-sa">
          <view
            class="btn"
            @click="
              () => {
                printShows = false;
              }
            "
          >
            <clIcon type="icon-dayin" color="#999" size="22"></clIcon>
            <text class="">打印</text>
          </view>
          <view class="btn" @click="preview">
            <u-icon name="search" color="#999" size="24"></u-icon>
            <text class="">预览</text>
          </view>
          <view class="btn">
            <u-icon name="share" color="#999" size="24"></u-icon>
            <text class="">分享</text>
          </view>
        </view>
      </view>
    </u-popup>
    <view :style="{ width: width + 'mm' }">
      <view id="preview_content" ref="previewContentRef"></view>
    </view>
    <cxPreviewImage
      ref="cxPreviewImage"
      :opacity="1"
      :circular="true"
      :imgs="imgsttt"
    ></cxPreviewImage>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>
<script>
import clIcon from "@/components/cl-icon/cl-icon.vue";
import cxPreviewImage from "@/components/cx-kxj-previewImage/cx-kxj-previewImage.vue"; //引用插件
import { hiprint, defaultElementTypeProvider } from "vue-plugin-hiprint";
import domtoimage from "dom-to-image";
import panels from "./panels2.js";
// var hiprintTemplate = null
// var filename = "";
export default {
  props: {
    printShow: {
      type: Boolean,
      default: false,
    },
    print: {
      type: Object,
      default: {},
    },
    bill: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      width: 200,
      printShows: false,
      imgsttt: [],
      filename: new Date().getTime().toString(),
      hiprintTemplate: null,
    };
  },
  components: {
    clIcon,
    cxPreviewImage,
  },
  onLoad() {
    this.$refs.uToast.show({
      type: "err",
      title: "",
      message: "请先选择报表",
    });
  },
  created() {
    hiprint.init();
    this.width = panels.panels[0].width;
  },
  watch: {
    printShow(n, old) {
      this.printShows = true;
    },
  },
  methods: {
    toPrinter() {
      this.$emit("toPrinter");
    },
    toReport() {
      this.$emit("toReport");
    },
    preview() {
      if (this.print.panels2 == null) {
        this.$refs.uToast.show({
          type: "error",
          title: "",
          position: "top",
          message: "请先选择报表",
        });
        return;
      }
      if(Object.keys(this.print.panels2.templateData).length === 0){
        this.$refs.uToast.show({
          type: "error",
          title: "",
          position: "top",
          message: "请先去后台设置模版",
        });
        return;
      }
      return
      uni.showLoading({
        title: "加载中",
      });
      this.openqa();
    },
    async openqa() {
      await this.waitMinute();
      // this.$refs.previewContentRef.innerHTML = '';
      this.bill.imgurl = this.setImg("components/cx-print/20230902151801.jpg");
      //预览并打印
      this.hiprintTemplate = new hiprint.PrintTemplate({
        template: this.print.panels2.templateData,
      });
      // hiprintTemplate = new hiprint.PrintTemplate({
      //   template: panels
      // });
      var html = this.hiprintTemplate.getHtml(this.bill);
      html[0].style.backgroundColor = "white";
      // this.$refs.previewContentRef.appendChild(html[0]);
      await this.createImg();
      //打印
    },
    async createImg() {
      this.$refs.previewContentRef.innerHTML = "";
      var html = this.hiprintTemplate.getHtml(this.bill);
      html[0].style.backgroundColor = "white";
      // html[0].style.position = 'absolute';
      // html[0].style.left = '-100000px';
      const praHtml = [...html[0].childNodes[0].childNodes];
      const praHtmlCount = praHtml.length;
      let url = [];
      for (let i = 0; i < praHtmlCount - 3; i++) {
        html[0].childNodes[0].innerHTML = "";
        html[0].childNodes[0].appendChild(praHtml[0]);
        html[0].childNodes[0].appendChild(praHtml[1]);
        html[0].childNodes[0].appendChild(praHtml[2]);
        html[0].childNodes[0].appendChild(praHtml[3 + i]);
        this.$refs.previewContentRef.$el.appendChild(html[0]);

        // filename = this.filename + '(' + i + ')';
        await this.waitMinute();
        let iss = await this.jjkimg(html[0]);
        url.push(this.convertBase64ToImg(iss));
      }
      this.imgsttt = url;
      this.printShows = false;
      uni.hideLoading();
      this.$refs.cxPreviewImage.open(this.imgsttt[0]);
    },
    convertBase64ToImg(base64Img) {
      var byteString = atob(base64Img.split(",")[1]);
      var mimeString = base64Img.split(",")[0].split(":")[1].split(";")[0];
      var ab = new ArrayBuffer(byteString.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      var blob = new Blob([ab], {
        type: mimeString,
      });
      return URL.createObjectURL(blob);
    },
    setImg(imgUrl) {
      return require("@/" + imgUrl);
    },
    // 让程序等待一下
    async waitMinute() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(1);
        }, 200);
      });
    },
    // 画图并下载
    async jjkimg(str) {
      return new Promise((resolve, reject) => {
        domtoimage
          .toPng(str)
          .then((dataUrl) => {
            // downloadFileByBase64(dataUrl, filename);
            resolve(dataUrl);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    downloadFile(url, name) {
      var a = document.createElement("a"); //新建一个a链接
      a.setAttribute("href", url); // a链接的url为图片的url
      a.setAttribute("download", name);
      a.setAttribute("target", "_blank");
      let clickEvent = document.createEvent("MouseEvents");
      clickEvent.initEvent("click", true, true);
      a.dispatchEvent(clickEvent);
    },

    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime,
      });
    },

    downloadFileByBase64(base64, name) {
      var myBlob = dataURLtoBlob(base64);
      var myUrl = URL.createObjectURL(myBlob); //创建图片的临时url
      this.downloadFile(myUrl, name);
    },
  },
};
</script>
<style lang="scss"  scoped>
#preview_content {
  transform-origin: top left;
  transform: scale(0.01, 0.01);
}

.btn {
  justify-content: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  line-height: 40rpx !important;
  padding: 14rpx 0 10rpx;
  color: #999 !important;
}

.cell-item {
  display: flex;
  height: 80rpx;
  border-bottom: 1rpx solid #eee;
  align-items: center;
  font-size: 30rpx;

  .label {
    width: 120rpx;
    text-align: right;
    color: #999;
  }

  .value-view {
    padding-left: 10rpx;
    padding-right: 20rpx;
    flex: 1;
    justify-content: space-between;
  }
}

.title-view {
  display: flex;
  padding: 0 20rpx;
  background-color: #efefef;
  border-radius: 12rpx 12rpx 0 0;
  height: 80rpx;
  align-items: center;

  .text-view {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
  }
}
</style>